<template>
  <div class="Modify-form">
    <div class="app-main-top-box">
      <div class="title" style="height: 31px;line-height: 31px">
        批量操作
        <el-button type="primary" style="margin-left: 30px" size="small" round @click="vipNumber">提交</el-button>
      </div>
    </div>
    <el-divider />
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" size="small">
      <el-form-item label="操作目的：" prop="operation">
        <el-radio-group v-model="form.operation" @change="operationChange">
          <el-radio v-if="!$store.getters.banBtnList.includes('MCH_TAB_BATCH_CHANGE_BALANCE')" :label="1">余额充值</el-radio>
          <el-radio v-if="!$store.getters.banBtnList.includes('MCH_TAB_BATCH_CHANGE_BALANCE')" :label="2">余额扣除</el-radio>
          <el-radio v-if="!$store.getters.banBtnList.includes('MCH_TAB_BATCH_CHANGE_POINTS')" :label="3">赠送积分</el-radio>
          <el-radio v-if="!$store.getters.banBtnList.includes('MCH_TAB_BATCH_CHANGE_POINTS')" :label="4">扣除积分</el-radio>
          <!--          <el-radio-->
          <!--            v-if="!$store.getters.banBtnList.includes('MCH_TAB_BATCH_SEND_COUPON')"-->
          <!--            :label="5"-->
          <!--          >赠送优惠券-->
          <!--          </el-radio>-->
          <el-radio v-if="!$store.getters.banBtnList.includes('MCH_TAB_BATCH_SEND_COUPON')" :label="6">赠送卡券</el-radio>
          <el-radio v-if="!$store.getters.banBtnList.includes('MCH_BTN_MEMBER_TAGS_EDIT')" :label="7">打标签</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 余额 -->
      <div v-if="form.operation === 1 || form.operation === 2">
        <el-form-item prop="real" label="实充金额：">
          <el-input v-model="form.real" placeholder="请输入，不调整输0" maxlength="10" class="w-300">
            <template slot="append">
              元
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="given" label="赠送金额：">
          <el-input v-model="form.given" placeholder="请输入，不调整输0" maxlength="10" class="w-300">
            <template slot="append">
              元
            </template>
          </el-input>
        </el-form-item>
      </div>

      <!-- 积分 -->
      <el-form-item v-if="form.operation === 3 || form.operation === 4" prop="points" label="积分个数：">
        <el-input v-model.trim="form.points" placeholder="请输入" maxlength="7" class="w-300">
          <template slot="append">
            个
          </template>
        </el-input>
      </el-form-item>

      <!-- 赠送卡券 -->
      <el-form-item v-if="form.operation === 6 || form.operation === 5" :label="form.operation === 6 ? '赠送卡券' : '赠送券'" prop="couponSendData">
        <div class="card-coupon-container">
          <el-table :data="form.couponSendData" border stripe size="small" empty-text="暂未配置" style="width: 100%">
            <el-table-column prop="couponId" label="批次号" />
            <el-table-column prop="couponName" label="卡券名称" />
            <el-table-column prop="couponType" label="卡券类型">
              <template slot-scope="scope">
                {{ $store.getters.cardCouponTypeKeyOptions[scope.row.couponType] || '--' }}
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="数量" width="170px">
              <template slot-scope="scope">
                <el-form-item :prop="'couponSendData[' + scope.$index + '].amount'" :rules="rules.couponBonusAmount">
                  <el-input-number v-model="scope.row.amount" :min="1" :max="99" maxlength="2" label="数量" style="margin-top: 18px" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template slot-scope="scope">
                <el-button type="text" @click="delCardCoupon(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button
            v-if="form.operation === 6"
            :disabled="form.couponSendData.length >= 10"
            type="text"
            icon="el-icon-plus"
            style="display:block"
            @click.native.prevent="openDialogCardCouponTable"
          >
            增加卡券
          </el-button>
          <!--          <el-button-->
          <!--            v-if="form.operation===5"-->
          <!--            :disabled="form.couponSendData.length>=10"-->
          <!--            type="text"-->
          <!--            icon="el-icon-plus"-->
          <!--            style="display:block"-->
          <!--            @click.native.prevent="openCouponList"-->
          <!--          >增加券-->
          <!--          </el-button>-->
          <div style="font-size: 12px;color: #606266">单次最多添加卡券种类不超过10种，卡券总数量不超过30张（因为微信限制，暂不支持配置微信商家券）</div>
        </div>
      </el-form-item>

      <!-- 打标签 -->
      <div v-if="form.operation === 7">
        <el-form-item prop="addTags" label="新加的标签：">
          <div v-for="(item, index) in form.addTags" :key="index" class="form-hobby-val app-border-color-primary">
            <span>{{ item.tagName }}</span>
            <i class="el-icon-close" @click="removeTag(index, 'addTags')" />
          </div>
          <el-button type="text" icon="el-icon-plus" size="small" @click="tagDialogOpen('add')">选择标签</el-button>
        </el-form-item>
        <el-form-item prop="removeTags" label="移除的标签：">
          <div v-for="(item, index) in form.removeTags" :key="index" class="form-hobby-val app-border-color-primary">
            <span>{{ item.tagName }}</span>
            <i class="el-icon-close" @click="removeTag(index, 'removeTags')" />
          </div>
          <el-button type="text" icon="el-icon-plus" size="small" @click="tagDialogOpen('remove')">选择标签</el-button>
        </el-form-item>
      </div>

      <!-- 备注 -->
      <el-form-item prop="remark" label="备注：">
        <el-input v-model="form.remark" :autosize="{ minRows: 2, maxRows: 10 }" type="textarea" class="w-300" placeholder="请输入备注" maxlength="50" show-word-limit />
      </el-form-item>

      <!-- 添加/移除标签弹窗 -->
      <el-dialog :visible.sync="tagDialogVisible" :close-on-click-modal="false" :title="tagDialogTitle" width="750px" @close="tagDialogClose(tagDialogType)">
        <!--      <el-form ref="form" :model="form" label-width="120px" size="small" inline>-->
        <el-form-item label="标签：">
          <div v-for="(item, index) in labelGroup" :key="index">
            <el-form-item>
              <div style="margin: 0 0 10px 5px">{{ item.tagGroup }}</div>
              <el-button
                v-for="v in item.tags"
                :key="v.id"
                :type="form[tagDialogType] ? (form[tagDialogType].includes(v.id) ? 'primary' : '') : form[tagType].includes(v.id) ? 'primary' : ''"
                round
                @click="multipleChoice(tagDialogType, v.id)"
              >
                {{ v.tagName }}
              </el-button>
            </el-form-item>
          </div>
        </el-form-item>
        <!--      </el-form>-->
        <div slot="footer" class="dialog-footer">
          <el-button size="medium" round @click="tagDialogClose(tagDialogType)">取 消</el-button>
          <el-button size="medium" round type="primary" @click="tagDialogConfirm(tagDialogType)">确 认</el-button>
        </div>
      </el-dialog>

      <!-- 计算人数确认弹窗 -->
      <el-dialog :visible.sync="memberNumVisible" :close-on-click-modal="false" title="提交确认" width="750px" @close="memberNumClose">
        <!--      <el-form ref="form" :model="form" label-width="120px" size="small">-->
        <el-form-item v-if="filterForm.type !== 3" label="操作会员数：">
          <div style="font-size: 16px; font-weight: bolder">{{ memberNum }}</div>
        </el-form-item>
        <div v-if="form.operation === 1 || form.operation === 2">
          <el-form-item label="操作：">
            <div>{{ form.operation === 1 ? '余额充值' : '余额扣除' }}</div>
          </el-form-item>
          <el-form-item label="实充余额：">
            <div>{{ form.real || 0 }} 元</div>
          </el-form-item>
          <el-form-item label="赠送金额：">
            <div>{{ form.given || 0 }} 元</div>
          </el-form-item>
        </div>
        <div v-if="form.operation === 3 || form.operation === 4">
          <el-form-item label="操作：">
            <div>{{ form.operation === 3 ? '赠送积分' : '扣除积分' }}</div>
          </el-form-item>
          <el-form-item label="积分个数：">
            <div>{{ form.points }} 个</div>
          </el-form-item>
        </div>
        <div v-if="form.operation === 5 || form.operation === 6">
          <el-form-item label="操作：">
            <div>{{ form.operation === 5 ? '赠送优惠券' : '赠送卡券' }}</div>
          </el-form-item>
          <el-table :data="form.couponSendData" border stripe size="small" empty-text="暂未配置" style="width: 100%">
            <el-table-column prop="couponId" label="批次号" />
            <el-table-column prop="couponName" label="卡券名称" />
            <el-table-column prop="couponType" label="卡券类型">
              <template slot-scope="scope">
                {{ $store.getters.cardCouponTypeKeyOptions[scope.row.couponType] || '--' }}
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="数量" />
          </el-table>
        </div>
        <div v-if="form.operation === 7">
          <el-form-item label="操作："><div>更新标签</div></el-form-item>
          <el-form-item label="添加标签：">
            <div v-for="(item, index) in form.addTags" :key="index" class="form-hobby-val app-border-color-primary">
              <span>{{ item.tagName }}</span>
            </div>
            <div v-if="!form.addTags.length">（无）</div>
          </el-form-item>
          <el-form-item label="移除标签：">
            <div v-for="(item, index) in form.removeTags" :key="index" class="form-hobby-val app-border-color-primary">
              <span>{{ item.tagName }}</span>
            </div>
            <div v-if="!form.removeTags.length">（无）</div>
          </el-form-item>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button size="medium" round @click="memberNumClose">取 消</el-button>
          <el-button size="medium" round type="primary" @click="submit">确认操作</el-button>
        </div>
      </el-dialog>
    </el-form>
    <el-form ref="filterForm" :model="filterForm" :rules="rules" label-width="120px" size="small" inline>
      <el-form-item label="筛选方式：" prop="type">
        <el-select v-model="filterForm.type" placeholder="请选择"><el-option v-for="(v, k) in typeOptions" :key="k" :label="v" :value="Number(k)" /></el-select>
      </el-form-item>
      <!-- 筛选条件 -->
      <div v-if="filterForm.type === 1">
        <el-form-item label="来源：" prop="source">
          <el-select v-model="filterForm.source" placeholder="请选择" collapse-tags clearable style="max-width: 180px">
            <el-option v-for="item in source" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="余额大于：" prop="minBalance">
          <el-input v-model.trim="filterForm.minBalance" placeholder="请输入数字" type="text" size="small" clearable style="max-width: 180px" />
        </el-form-item>
        <el-form-item label="余额小于：" prop="maxBalance">
          <el-input v-model.trim="filterForm.maxBalance" placeholder="请输入数字" type="text" size="small" clearable style="max-width: 180px" />
        </el-form-item>
        <el-form-item label="积分大于：" prop="minPoints">
          <el-input v-model.trim="filterForm.minPoints" placeholder="请输入数字" type="text" size="small" clearable style="max-width: 180px" />
        </el-form-item>
        <el-form-item label="积分小于：" prop="maxPoints">
          <el-input v-model.trim="filterForm.maxPoints" placeholder="请输入数字" type="text" size="small" clearable style="max-width: 180px" />
        </el-form-item>
        <el-form-item label="注册门店：" prop="shopId">
          <el-select
            v-model="filterForm.shopId"
            filterable
            multiple
            collapse-tags
            clearable
            placeholder="可通过名称搜索"
            style="max-width: 180px"
            @change="val => idsChange(val, 'shop')"
          >
            <el-option label="全部门店" value />
            <el-option v-for="(item, index) in manageShopList" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="性别：" prop="sex">-->
        <!--          <el-select-->
        <!--            v-model="filterForm.sex"-->
        <!--            placeholder="请选择"-->
        <!--            collapse-tags-->
        <!--            clearable-->
        <!--            style="max-width: 180px"-->
        <!--          >-->
        <!--            <el-option-->
        <!--              v-for="item in sex"-->
        <!--              :key="item.value"-->
        <!--              :label="item.label"-->
        <!--              :value="item.value"-->
        <!--            />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item label="已注册时长大于:" prop="registerEndTime">
          <el-input v-model.trim="filterForm.endYear" :disabled="registerEndTime" style="width: 50px" maxlength="2" @change="dateChange" />
          年
          <el-input v-model.trim="filterForm.endMonth" :disabled="registerEndTime" style="width: 50px" maxlength="2" @change="dateChange" />
          月
          <el-input v-model.trim="filterForm.endDay" :disabled="registerEndTime" style="width: 50px" maxlength="2" @change="dateChange" />
          日
        </el-form-item>
        <el-form-item label="已注册时长小于:" prop="registerStartTime">
          <el-input v-model.trim="filterForm.startYear" :disabled="registerStartTime" style="width: 50px" maxlength="2" @change="dateChange" />
          年
          <el-input v-model.trim="filterForm.startMonth" :disabled="registerStartTime" style="width: 50px" maxlength="2" @change="dateChange" />
          月
          <el-input v-model.trim="filterForm.startDay" :disabled="registerStartTime" style="width: 50px" maxlength="2" @change="dateChange" />
          日
        </el-form-item>
        <br>
        <el-form-item label="持卡：">
          <el-button :type="form.memberCategoryId.length === cardList.length ? 'primary' : ''" round @click="multipleChoice('all')">全部</el-button>
          <el-button
            v-for="v in cardList"
            :key="v.id"
            :type="form.memberCategoryId.includes(v.id) ? 'primary' : ''"
            round
            @click="multipleChoice('memberCategoryId', v.id)"
          >
            {{ v.categoryName }}
          </el-button>
        </el-form-item>
        <br>
        <el-form-item label="标签：">
          <el-button type="text" size="medium" style="padding: 0" @click="isShowMoreFilter = !isShowMoreFilter">
            {{ isShowMoreFilter ? '收起' : '展开' }}所有标签
          </el-button>
          <el-collapse-transition>
            <div v-show="isShowMoreFilter">
              <div v-for="(item, index) in labelGroup" :key="index">
                <el-form-item>
                  <div style="color: #666;margin: 0 0 10px 10px">{{ item.tagGroup }}</div>
                  <el-button v-for="v in item.tags" :key="v.id" :type="form.tagId.includes(v.id) ? 'primary' : ''" round @click="multipleChoice('tagId', v.id)">
                    {{ v.tagName }}
                  </el-button>
                </el-form-item>
              </div>
            </div>
          </el-collapse-transition>
        </el-form-item>
      </div>

      <!-- 会员分群 -->
      <el-form-item v-if="judgeOpen == 1 && filterForm.type === 1" label="会员分群：" prop="type">
        <el-select v-model="memberGroupsName" placeholder="请选择会员分群" @change="memberGroupChange($event)">
          <el-option v-for="item in memberGroups" :key="item.id" :label="item.groupName" :value="item.id" />
        </el-select>
      </el-form-item>

      <!-- 手机号 -->
      <div v-if="filterForm.type === 2">
        <el-form-item label="会员手机号：" prop="phonesStr">
          <el-input
            v-model="filterForm.phonesStr"
            :autosize="{ minRows: 10, maxRows: 20 }"
            type="textarea"
            placeholder="请输入会员手机号， 一行一个(Enter换行)"
            class="w-300"
            @focus="$refs.form.clearValidate(['phonesStr'])"
          />
          <div>请输入会员手机号，单次最多输入50个，一行一个(回车键Enter换行)</div>
        </el-form-item>
      </div>
      <!-- excel导入 -->
      <div v-if="filterForm.type === 3">
        <el-form-item label="上传excel：" prop="file">
          <el-upload
            ref="upload"
            :action="uploadExcelUrl"
            :multiple="false"
            :limit="1"
            :headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }"
            :on-success="handleExcelSuccess"
            :before-upload="beforeExcelUpload"
            class="upload-container"
            drag
          >
            <i class="el-icon-upload" />
            <div class="el-upload__text">
              将excel文件拖到此处，或
              <em>点击上传</em>
            </div>
          </el-upload>
          <div>
            先下载EXCEL模板，按照要求填写后上传文档进行导入，
            <a class="app-text-color-primary" @click.prevent="downTemplate"><u>点击下载模板</u></a>
            。
          </div>
        </el-form-item>
      </div>
    </el-form>

    <!-- 弹框券 -->
    <DialogCouponList ref="dialogCouponList" />
    <!--券2.0 筛选表格 -->
    <DialogCardCouponTable ref="dialogCardCouponTable" :card-coupon-type="['cash', 'discount', 'exchange', 'times', 'gift']" :has-checked-ids="hasCheckedCardCouponIds" />
  </div>
</template>

<script>
import DialogCardCouponTable from '@/components/DialogCardCouponTable'
import DialogCouponList from '@/components/DialogCouponList'
import { mapGetters } from 'vuex'
import { getAllVipCardList, memberBatchJobMemberNum, memberBatchJobForm, getTagsList, getMemberGroups, judgeOpenRfm } from '@/api/vip'
import { batchJobFileUploadUrl } from '@/api/upload'
import { validateCustomPositiveInt, validateCustomTwoDecimal, validateMobilePhone } from '@/utils/validate'
import { test2Decimal } from '@/utils/validator'

export default {
  components: {
    DialogCouponList,
    DialogCardCouponTable
  },
  props: {
    selectOption: null,
    selectGroupId: null
  },
  data() {
    // 手机号
    const validatePhonesStr = (rule, value, callback) => {
      if (!value) {
        callback('请输入手机号')
      } else {
        const phoneArr = value
          .trim()
          .replace(/\ */g, '')
          .replace(/\n/g, ',')
          .replace(/,+/g, ',')
          .split(',')
        if (phoneArr.length > 50) callback('手机号单次最多50个')
        let result = false
        result = phoneArr.some((v, i) => {
          if (!validateMobilePhone(v)) {
            callback(`手机号格式有误（第${i + 1}个手机号：（${v}））`)
            return true
          }
        })
        if (!result) callback()
      }
    }
    // 校验数字
    const validateNumber = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (!validateCustomPositiveInt(value, 7)) {
        callback(new Error('请输入0.01~9999999.99'))
      } else {
        callback()
      }
    }
    // 校验金额
    const validateBalance = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (!validateCustomTwoDecimal(value, 7)) {
        callback(new Error('请输入0.01~9999999.99'))
      } else {
        callback()
      }
    }
    // 实充余额
    const validateReal = (rule, value, callback) => {
      if ((this.$isNull(value) && this.$isNull(this.form.given)) || (Number(value) === 0 && Number(this.form.given) === 0)) {
        callback(new Error('至少设置一种进行调整'))
      } else if (!test2Decimal(value, 0.01, 99999.99, [0])) {
        callback(new Error('请输入0~99999.99'))
      } else {
        callback()
        if (this.form.given && test2Decimal(this.form.given, 0.01, 99999.99, [0])) this.$refs.form.clearValidate(['given'])
      }
    }
    // 赠送余额
    const validateGiven = (rule, value, callback) => {
      if ((this.$isNull(value) && this.$isNull(this.form.real)) || (Number(value) === 0 && Number(this.form.real) === 0)) {
        callback(new Error('至少设置一种进行调整'))
      } else if (!test2Decimal(value, 0.01, 99999.99, [0])) {
        callback(new Error('请输入0~99999.99'))
      } else {
        callback()
        if (this.form.real && test2Decimal(this.form.real, 0.01, 99999.99, [0])) this.$refs.form.clearValidate(['real'])
      }
    }
    // 积分个数
    const validatePoints = (rule, value, callback) => {
      if (this.$isNull(value)) {
        callback('请输入数量')
      } else if (!validateCustomPositiveInt(value, 7)) {
        callback(new Error('请输入正整数'))
      } else {
        callback()
      }
    }
    // 奖励优惠券
    const validateCouponBonusAmount = (rule, value, callback) => {
      if (this.$isNull(value)) {
        callback('请输入数量')
      } else if (!validateCustomPositiveInt(value, 2)) {
        callback(new Error('请输入正整数'))
      } else {
        this.$refs.form.validateField(['couponSendData'])
        callback()
      }
    }
    // 奖励优惠券
    const validateCouponBonus = (rule, value, callback) => {
      if (!value.length) {
        callback('请至少选择一种')
      } else if (value.length > 10) {
        callback('卡券种类不超过10种')
      } else {
        let maxAmount = 0
        value.forEach(v => {
          if (validateCustomPositiveInt(v.amount, 2)) {
            maxAmount += v.amount
          }
        })
        if (maxAmount > 30) {
          callback('卡券总数量不超过30张')
        } else {
          callback()
        }
      }
    }
    // 标签修改
    const validateChangeTag = (rule, value, callback) => {
      if (this.form.addTags.length === 0 && this.form.removeTags.length === 0) {
        callback('至少设置一种进行调整')
      } else {
        // this.$refs.form.resetFields(['addTags'])
        // this.$refs.form.resetFields(['removeTags'])
        callback()
      }
    }
    return {
      // 校验字段
      rules: {
        // 余额
        minBalance: [{ validator: validateBalance, trigger: 'blur' }],
        maxBalance: [{ validator: validateBalance, trigger: 'blur' }],
        // 积分
        minPoints: [{ validator: validateNumber, trigger: 'blur' }],
        maxPoints: [{ validator: validateNumber, trigger: 'blur' }],
        // 手机号
        phonesStr: [
          {
            required: true,
            validator: validatePhonesStr,
            trigger: ['blur']
          }
        ],
        // 上传表格
        // file: [
        //   {
        //     required: true,
        //     message: '请上传excel',
        //     trigger: 'change'
        //   }
        // ],
        // 操作内容
        operation: [
          {
            required: true,
            message: '请选择操作内容',
            trigger: 'change'
          }
        ],
        // 实冲余额
        real: [{ required: true, validator: validateReal, trigger: 'blur' }],
        // 赠送余额
        given: [{ required: true, validator: validateGiven, trigger: 'blur' }],
        // 积分
        points: [{ required: true, validator: validatePoints, trigger: 'blur' }],
        // 优惠券数量
        couponBonusAmount: [
          {
            required: true,
            validator: validateCouponBonusAmount,
            trigger: ['blur', 'change']
          }
        ],
        // 券列表
        couponSendData: [
          {
            type: 'array',
            required: true,
            validator: validateCouponBonus,
            trigger: ['blur', 'change']
          }
        ],
        // 标签修改
        addTags: [
          {
            require: true,
            validator: validateChangeTag
          }
        ],
        removeTags: [
          {
            require: true,
            validator: validateChangeTag
          }
        ],

        // 备注
        remark: [
          {
            required: true,
            message: '请输入备注',
            trigger: ['change']
          }
        ]
      },
      // 配置
      typeOptions: {
        1: '按筛选条件选择会员',
        2: '按手机号筛选会员',
        3: '通过Excel筛选会员'
      },
      uploadExcelUrl: batchJobFileUploadUrl, // 上传地址
      // 状态
      loading: false,
      registerStartTime: false, // 时间输入框状态
      registerEndTime: false, // 时间输入框状态
      isShowMoreFilter: false,
      // 数据
      shopId: [], // 所有门店ids
      cardList: [], // 卡列表数据
      categoryId: [], // 所有卡ids
      hasCheckedCardCouponIds: [], // 已选择券id
      labelGroup: [], // 标签组
      // 标签弹窗数据
      tagDialogVisible: false, // 弹窗状态
      tagDialogTitle: null, // 弹窗标题
      tagType: 'addTags', // 弹窗初始值
      tagDialogType: 'addTagsDemo', // 弹窗类型
      // 会员人数计算确认弹窗
      memberNumVisible: false, // 弹窗状态
      memberNum: 0, // 操作会员数量
      filterParams: {}, // 筛选条件使用的参数
      filterForm: {
        startYear: '',
        startMonth: '',
        startDay: '',
        endYear: '',
        endMonth: '',
        endDay: '',
        type: 1, // 来源
        source: null,
        minBalance: null, // 余额大于
        maxBalance: null, // 余额小于
        minPoints: null, // 积分大于
        maxPoints: null, // 积分小于
        registerEndTime: null, // 注册晚于
        registerStartTime: null, // 注册早于
        shopId: [], // 门店
        // sex: null, // 性别
        phonesStr: null, // 手机号
        phones: [], // 手机号
        file: null, // 文件
        memberGroupId: '' // 会员分群id
      },
      form: {
        tagId: [], // 标签(特殊)
        memberCategoryId: [], // 会员卡类型(特殊)
        operation: 1, // 调整类型
        real: null, // 实充值
        given: null, // 赠送
        points: null, // 积分
        couponSendData: [], // 赠送优惠券信息
        addTags: [], // 添加的标签
        removeTags: [], // 移除的标签
        addTagsDemo: [], // 添加的标签模板
        removeTagsDemo: [], // 移除的标签模板
        remark: null, // 说明
        memberGroupId: '' // 会员分群id
      },
      /**
			 * 下拉框内容
			 */
      source: [
        {
          value: 1,
          label: '线上开卡'
        },
        {
          value: 2,
          label: '门店推广'
        },
        {
          value: 3,
          label: '员工推广'
        },
        {
          value: 4,
          label: '会员分享'
        },
        {
          value: 5,
          label: '第三方平台'
        },
        {
          value: 6,
          label: '支付即会员'
        },
        {
          value: 7,
          label: '会员赠送'
        },
        {
          value: 8,
          label: '会员导入'
        }
      ], // 来源条件
      // sex: [
      //   {
      //     value: '1',
      //     label: '男'
      //   },
      //   {
      //     value: '0',
      //     label: '女'
      //   },
      //   {
      //     value: '-1',
      //     label: '未知'
      //   }
      // ] // 性别

      // 会员分群
      memberGroups: [
        {
          value: '活跃会员',
          label: '活跃会员'
        }
      ],
      memberGroupsName: '',
      judgeOpen: null
    }
  },
  computed: {
    ...mapGetters(['manageShopList', 'banBtnList', 'fileBaseUrl'])
  },
  watch: {
    'filterForm.type'() {
      this.$refs.filterForm.clearValidate(['minBalance', 'maxBalance', 'minPoints', 'maxPoints', 'phonesStr', 'file'])

      if (this.filterForm.type != 1) {
        this.filterForm.memberGroupId = ''
        this.form.memberGroupId = ''
        this.memberGroupsName = null
      }
    },
    'form.operation'() {
      this.$refs.form.clearValidate(['real', 'given', 'points', 'couponSendData', 'addTags', 'removeTags', 'remark'])
    }
  },
  created() {
    this.judgeOpenRfmFun()
  },
  mounted() {
    console.log(this.selectOption)
    if (this.selectOption) {
      this.form.operation = this.selectOption
    } else if (!this.banBtnList.includes('MCH_TAB_BATCH_CHANGE_BALANCE')) {
      this.form.operation = 1
    } else if (!this.banBtnList.includes('MCH_TAB_BATCH_CHANGE_POINTS')) {
      this.form.operation = 3
    } else if (!this.banBtnList.includes('MCH_TAB_BATCH_SEND_COUPON')) {
      this.form.operation = 6
    } else if (!this.banBtnList.includes('MCH_TAB_BATCH_SEND_COUPON')) {
      this.form.operation = 7
    }
    this.fetchData()
    this.getTagList()
  },
  methods: {
    /**
		 * 数据组
		 */
    // 获取数据
    fetchData() {
      this.loading = true
      getAllVipCardList()
        .then(res => {
          this.cardList = res.data
          this.getIds()
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false
        })
    },

    // 获取所有Ids
    getIds() {
      const shopId = ['']
      const categoryId = ['']
      this.manageShopList.forEach(v => {
        shopId.push(v.id)
      })
      this.cardList.forEach(v => {
        categoryId.push(v.id)
      })
      this.shopId = shopId
      this.categoryId = categoryId
    },

    // 获取标签列表信息
    getTagList() {
      this.data = []
      getTagsList().then(res => {
        res.data.forEach(e => {
          if (e.tags.length) {
            this.labelGroup.push(e)
          }
        })
      })
    },

    // 通过手机号批量操作
    batchOption(selected = []) {
      this.filterForm.type = 2
      selected.forEach(e => this.filterForm.phones.push(e))
      this.filterForm.phonesStr = this.filterForm.phones.join('\n')
    },
    /**
		 * 按钮组
		 */
    // 下载模板
    downTemplate() {
      const alink = document.createElement('a')
      alink.href = this.fileBaseUrl + 'business/template/batch_operation_template.xlsx'
      alink.download = ''
      alink.click()
    },

    // 上传excel前
    beforeExcelUpload(file) {
      if (this.beforeUploadExcel(file, this, 1)) {
        this.loading = true
        return true
      } else {
        return false
      }
    },

    // 上传excel后
    handleExcelSuccess(res, file) {
      this.loading = false
      if (res.code === 0) {
        this.form.file = res.data
      } else {
        this.loading = false
        this.$refs.upload.clearFiles()
        this.$message.error(res.msg)
      }
    },

    // 新增优惠券
    // openCouponList() {
    //   this.hasCheckedCardCouponIds = []
    //   this.form.couponSendData.forEach(v => {
    //     this.hasCheckedCardCouponIds.push(v.couponId)
    //   })
    //   this.$nextTick(() => {
    //     this.$refs.dialogCouponList.open(this.hasCheckedCardCouponIds, 1).then((res) => {
    //       this.$refs.form.clearValidate(['couponSendData'])
    //       const params = Object.assign({}, res)
    //       // const params = {
    //       //   couponId: res.id,
    //       //   amount: 1,
    //       //   couponName: res.couponName
    //       // }
    //       this.form.couponSendData.push(params)
    //     })
    //   })
    // },

    //  新增优惠券 v2
    openDialogCardCouponTable() {
      this.hasCheckedCardCouponIds = []
      this.form.couponSendData.forEach(v => {
        this.hasCheckedCardCouponIds.push(v.couponId)
      })
      this.$nextTick(() => {
        this.$refs.dialogCardCouponTable.open().then(res => {
          this.$refs.form.clearValidate(['couponSendData'])
          this.form.couponSendData = this.form.couponSendData.concat(res)
        })
      })
    },

    // 删除优惠券
    delCardCoupon(index) {
      this.form.couponSendData.splice(index, 1)
      if (this.form.couponSendData.length <= 10) {
        this.$refs.form.validateField(['couponSendData'])
      }
    },

    // 调整
    submit() {
      const params = JSON.parse(JSON.stringify(this.form))
      delete params.memberCategoryId
      delete params.tagId
      delete params.addTagsDemo
      delete params.removeTagsDemo
      if (params.operation === 6) params.operation = 5
      if (params.operation === 7) params.operation = 6
      switch (params.operation) {
        case 1:
        case 2:
          params.real = params.real ? this.$math.mul(params.real, 100, 0) : 0
          params.given = params.given ? this.$math.mul(params.given, 100, 0) : 0
          params.points = null
          params.couponSendData = []
          params.addTags = []
          params.removeTags = []
          break
        case 3:
        case 4:
          params.real = 0
          params.given = 0
          params.couponSendData = []
          params.addTags = []
          params.removeTags = []
          break
        case 5:
          params.real = 0
          params.given = 0
          params.points = null
          params.couponSendData.forEach(v => {
            v.number = v.amount
            delete v.amount
          })
          params.addTags = []
          params.removeTags = []
          break
        case 6:
          params.real = 0
          params.given = 0
          params.points = null
          params.couponSendData = []
          params.addTags.length ? params.addTags.forEach((e, i) => (params.addTags[i] = e.id)) : delete params.addTags
          params.removeTags.length ? params.removeTags.forEach((e, i) => (params.removeTags[i] = e.id)) : delete params.removeTags
          break
      }
      // 清除多余字段
      for (const key in params) {
        if (Object.prototype.hasOwnProperty.call(params, key)) {
          if (params[key] === null || params[key] === '') {
            delete params[key]
          }
        }
      }
      const allParams = { ...params, ...this.filterParams }
      this.loading = true
      const _this = this
      memberBatchJobForm(allParams)
        .then(() => {
          this.$alert('操作已提交，我们将为您处理数据，请在历史记录查看。', '提示', {
            confirmButtonText: '查看',
            center: true,
            roundButton: true,
            type: 'success',
            callback: action => {
              _this.hasCheckedCardCouponIds = []
              _this.filterForm = {
                startYear: '',
                startMonth: '',
                startDay: '',
                endYear: '',
                endMonth: '',
                endDay: '',
                type: 1,
                source: null,
                minBalance: null,
                maxBalance: null,
                minPoints: null,
                maxPoints: null,
                registerEndTime: null,
                registerStartTime: null,
                shopId: [],
                // sex: null,
                phonesStr: null,
                phones: [],
                file: null
              }
              _this.form = {
                tagId: [],
                memberCategoryId: [],
                operation: 1,
                real: null,
                given: null,
                points: null,
                couponSendData: [],
                addTags: [],
                removeTags: [],
                addTagsDemo: [],
                removeTagsDemo: [],
                remark: null
              }
              _this.$emit('changeTabName', 'accountHistory')
            }
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 标签弹窗事件
    tagDialogOpen(type) {
      if (this.labelGroup.length) {
        this.tagDialogVisible = true
        const tagType = type === 'add' ? 'addTags' : 'removeTags'
        this.tagDialogTitle = type === 'add' ? '新增标签' : '移除标签'
        this.tagDialogType = type === 'add' ? 'addTagsDemo' : 'removeTagsDemo'
        if (this.form[tagType].length) {
          this.form[tagType].forEach(e => this.form[this.tagDialogType].push(e.id))
        }
      } else {
        this.$message.warning('标签库为空')
      }
    },
    tagDialogClose(type) {
      this.tagDialogVisible = false
      this.form[type] = []
    },
    tagDialogConfirm(type) {
      const tagGroup = []
      const res = []
      this.labelGroup.forEach(e => {
        if (e.tags.length) {
          e.tags.forEach(v => tagGroup.push(v))
        }
      })
      this.form[type].forEach(e => {
        res.push(...tagGroup.filter(item => item.id === e))
      })
      type === 'addTagsDemo' ? (this.form.addTags = res) : (this.form.removeTags = res)
      this.tagDialogClose(type)
      this.$refs.form.validateField(['addTags', 'removeTags'])
    },
    // 移除标签
    removeTag(index, type) {
      this.form[type].splice(index, 1)
    },

    // 会员人数计算确认弹窗
    vipNumber() {
      this.$refs.filterForm.validate(valid1 => {
        if (valid1) {
          this.$refs.form.validate((valid2, error) => {
            if (!valid2) {
              console.log(error)
              return
            }
            if (valid2) {
              if (this.filterForm.type === 1) {
                this.loading = true
                const params = JSON.parse(JSON.stringify(this.filterForm))
                this.form.tagId.length ? Object.assign(params, { tagIdList: this.form.tagId }) : ''
                this.form.memberCategoryId.length ? Object.assign(params, { categoryId: this.form.memberCategoryId }) : ''
                // 日期处理
                if (this.registerStartTime) {
                  let year = params.endYear ? new Date(Date.now()).getFullYear() - params.endYear : new Date(Date.now()).getFullYear()
                  let month = params.endMonth ? new Date(Date.now()).getMonth() + 1 - params.endMonth : new Date(Date.now()).getMonth() + 1
                  let day = params.endDay ? new Date(Date.now()).getDate() - params.endDay : new Date(Date.now()).getDate()
                  if (day <= 0) {
                    day += 28
                    month--
                  }
                  if (month <= 0) {
                    month += 12
                    year--
                  }
                  params.registerEndTime = year + '-' + month + '-' + day + ' 00:00:00'
                  // eslint-disable-next-line no-sequences
                  delete params.endYear
                  delete params.endMonth
                  delete params.endDay
                }
                if (this.registerEndTime) {
                  let year = params.startYear ? new Date(Date.now()).getFullYear() - params.startYear : new Date(Date.now()).getFullYear()
                  let month = params.startMonth ? new Date(Date.now()).getMonth() + 1 - params.startMonth : new Date(Date.now()).getMonth() + 1
                  let day = params.startDay ? new Date(Date.now()).getDate() - params.startDay : new Date(Date.now()).getDate()
                  if (day <= 0) {
                    day += 28
                    month--
                  }
                  if (month <= 0) {
                    month += 12
                    year--
                  }
                  params.registerStartTime = year + '-' + month + '-' + day + ' 00:00:00'
                  // eslint-disable-next-line no-sequences
                  delete params.startYear
                  delete params.startMonth
                  delete params.startDay
                }
                // 金额处理
                params.minBalance = params.minBalance ? params.minBalance * 100 : ''
                params.maxBalance = params.maxBalance ? params.maxBalance * 100 : ''
                // 清除多余字段
                for (const key in params) {
                  if (Object.prototype.hasOwnProperty.call(params, key)) {
                    if (params[key] === null || params[key] === '') {
                      delete params[key]
                    }
                  }
                }
                this.filterParams = params
                memberBatchJobMemberNum(params)
                  .then(res => {
                    if (res.data) {
                      this.memberNumVisible = true
                      this.memberNum = res.data
                      this.step = 1
                    } else {
                      this.$message.error('该条件下查无会员')
                    }
                  })
                  .finally(() => {
                    this.loading = false
                  })
              } else if (this.filterForm.type === 2) {
                this.filterForm.phones = [
                  ...new Set(
                    this.filterForm.phonesStr
                      .trim()
                    // .replace(/\ */g, '')
                      .replace(/\n/g, ',')
                    // .replace(/,+/g, ',')
                      .split(',')
                  )
                ]
                this.memberNumVisible = true
                this.memberNum = this.filterForm.phones.length
                this.filterParams = { type: 2, phones: this.filterForm.phones }
              } else {
                this.filterParams = { type: 3 }
                this.memberNumVisible = true
              }
            }
          })
        }
      })
    },
    memberNumClose() {
      this.memberNumVisible = false
    },

    /**
		 * 状态组
		 */
    // 日期输入框触发事件
    dateChange() {
      this.registerEndTime = !!(this.filterForm.startYear || this.filterForm.startMonth || this.filterForm.startDay)
      this.registerStartTime = !!(this.filterForm.endYear || this.filterForm.endMonth || this.filterForm.endDay)
    },
    // 类型多选查询
    multipleChoice(type, index) {
      if (type !== 'all') {
        if (this.form[type].includes(index)) {
          this.form[type].splice(this.form[type].indexOf(index), 1)
        } else {
          this.form[type].push(index)
        }
      } else if (this.form.memberCategoryId.length !== this.cardList.length) {
        this.form.memberCategoryId = []
        this.cardList.forEach(v => this.form.memberCategoryId.push(v.id))
      } else {
        this.form.memberCategoryId = []
      }
    },

    // 多选改变
    idsChange(val, type) {
      let lastIdsType = ''
      let idsType = ''
      switch (type) {
        case 'shop':
          lastIdsType = 'lastShopIdArr'
          idsType = 'shopId'
          break
        case 'card':
          lastIdsType = 'lastCategoryIdArr'
          idsType = 'categoryId'
          break
      }
      const lastVal = this[lastIdsType]
      if ((val.includes('') && (lastVal.length === 0 || !lastVal.includes(''))) || (!val.includes('') && !lastVal.includes('') && val.length === this[idsType].length - 1)) {
        this.form[idsType] = this[idsType]
      } else if (!val.includes('') && lastVal.includes('')) {
        this.form[idsType] = []
      } else if (val.includes('') && val.length !== this[idsType].length) {
        const index = val.findIndex(v => v === '')
        if (index !== -1) val.splice(index, 1)
        this.form[idsType] = val
      }
      this[lastIdsType] = this.form[idsType]
    },

    //  类型
    operationChange(val) {
      if (val === 5 || val === 6) {
        this.form.couponSendData = []
      }
    },
    // 会员分群
    judgeOpenRfmFun() {
      judgeOpenRfm().then(res => {
        this.judgeOpen = res.data
        if (this.judgeOpen == 1) {
          this.getMemberGroupsFun()
        }
      })
    },
    getMemberGroupsFun() {
      getMemberGroups().then(res => {
        this.memberGroups = res.data
        this.selectGroupIdFun()
      })
    },
    memberGroupChange(e) {
      this.form.memberGroupId = e
      this.filterForm.memberGroupId = e
    },
    selectGroupIdFun() {
      let groupIndex = ''
      this.memberGroups.forEach((el, index) => {
        if (el.id == this.selectGroupId) {
          groupIndex = index
        }
      })
      this.memberGroupsName = this.memberGroups[groupIndex].groupName
      this.form.memberGroupId = this.selectGroupId
      this.filterForm.memberGroupId = this.selectGroupId
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.Modify-form {
	background-color: #fff;
	padding: 30px 30px;
	width: 100%;
}

.form-hobby-val {
	display: inline-block;
	height: 30px;
	padding: 0 5px 0 10px;
	margin-right: 10px;
	border-width: 1px;
	border-style: solid;
	border-radius: 5px;
	line-height: 30px;
	font-size: 14px;
	color: $dark-font-color;
}

.el-icon-close {
	cursor: pointer;
}
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
/* 通用 */
.w-300 {
	width: 300px;
}

.mulit-select {
	width: 80%;
	max-width: 700px;
}

/* 上传 */
.upload-container {
	max-width: 450px;
}

/* 券列表 */
.card-coupon-container {
	max-width: 700px;
}

//.card-container {
//  margin-bottom: 10px;
//  max-width: 700px;
//  .coupon-list {
//    width: 100%;
//    height: 70px;
//    display: inline-flex;
//    align-items: center;
//    justify-content: space-between;
//    .coupon-info {
//      color: #606266;
//      margin-right: 30px;
//      line-height: 1.5;
//    }
//    .coupon-num {
//      margin-top: 18px;
//    }
//  }
//}
</style>
